import React, { useState } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Image, Alert, ActivityIndicator, RefreshControl } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { RootStackParamList } from '../navigation/AppNavigator';
import { Colors } from '../constants/colors';
import { User } from '../types';
import { merchantService, profileService } from '../services';

type InstructorManagementNavigationProp = StackNavigationProp<RootStackParamList>;



export default function InstructorManagementScreen() {
  const navigation = useNavigation<InstructorManagementNavigationProp>();
  const [mentors, setMentors] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [profile, setProfile] = useState<any>(null);

  // 加载导师列表
  const loadMentors = async () => {
    try {
      setLoading(true);

      // 先獲取用戶資料確認是商家
      const profileData = await profileService.getProfile();
      setProfile(profileData);

      if (profileData.merchant) {
        const result = await merchantService.getMentorList({ pageNum: 1, pageSize: 50 });
        setMentors(result.list || []);
      }
    } catch (error: any) {
      console.error('加載導師列表失敗:', error);
      Alert.alert('錯誤', '加載導師列表失敗');
    } finally {
      setLoading(false);
    }
  };

  // 下拉刷新处理
  const onRefresh = async () => {
    setRefreshing(true);
    await loadMentors();
    // 延迟一点时间再隐藏刷新指示器，提供更好的用户体验
    setTimeout(() => {
      setRefreshing(false);
    }, 500);
  };

  // 页面聚焦时重新加载数据
  useFocusEffect(
    React.useCallback(() => {
      loadMentors();
    }, [])
  );

  const handleAddInstructor = () => {
    navigation.navigate('AddInstructor');
  };

  // 删除导师关联
  const handleDeleteMentor = async (mentorId: number) => {
    Alert.alert(
      '確認刪除',
      '確定要刪除這個導師關聯嗎？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '刪除',
          style: 'destructive',
          onPress: async () => {
            try {
              await merchantService.deleteMentorAssociation(mentorId);
              Alert.alert('成功', '導師關聯已刪除');
              loadMentors(); // 重新加載數據
            } catch (error: any) {
              console.error('刪除導師關聯失敗:', error);
              Alert.alert('錯誤', error.message || '刪除導師關聯失敗');
            }
          }
        }
      ]
    );
  };

  const renderInstructorCard = ({ item }: { item: User }) => (
    <View style={styles.itemCard}>
      <Image
        source={{
          uri: item.profileImageUrl || 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?ixlib=rb-4.0.3&auto=format&fit=crop&w=80&h=80'
        }}
        style={styles.avatar}
      />
      <View style={{ flex: 1 }}>
        <Text style={styles.name}>{item.username}</Text>
        <View style={styles.metaRow}>
          <Ionicons name="business-outline" size={14} color={Colors.gray[500]} />
          <Text style={styles.metaText}> {item.mentorName || ''}</Text>
          <Ionicons name="call-outline" size={14} color={Colors.gray[500]} style={{ marginLeft: 8 }} />
          <Text style={styles.metaText}> {item.tel || ''}</Text>
        </View>
        <View style={styles.badgeRow}>
          {/*{(item.qualifications || ['一級教練證照', '機構認證']).slice(0,2).map((q, idx) => (*/}
          {/*  <View key={idx} style={styles.badgeBlue}><Text style={styles.badgeText}>{q}</Text></View>*/}
          {/*))}*/}
          <View  style={styles.badgeBlue}><Text style={styles.badgeText}>{item.credentials}</Text></View>

        </View>
      </View>
      <TouchableOpacity
        style={styles.removePill}
        onPress={() => handleDeleteMentor(item.id)}
      >
        <Text style={styles.removePillText}>移除導師</Text>
      </TouchableOpacity>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      <LinearGradient colors={[Colors.gradientStart, Colors.gradientEnd]} style={styles.gradHeader}>
        <View style={styles.headerRow}>
          <Text style={styles.headerTitle}>導師管理</Text>
          <TouchableOpacity onPress={handleAddInstructor} style={styles.addPill}>
            <Text style={styles.addPillText}>＋ 添加導師</Text>
          </TouchableOpacity>
        </View>
      </LinearGradient>

      <View style={styles.content}>
        {loading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={Colors.primary} />
            <Text style={styles.loadingText}>加載導師列表...</Text>
          </View>
        ) : mentors.length === 0 ? (
          <View style={styles.emptyState}>
            <Ionicons name="people-outline" size={64} color={Colors.gray[400]} />
            <Text style={styles.emptyTitle}>暫無導師</Text>
            <Text style={styles.emptyDescription}>點擊右上角新增按鈕添加您的第一個導師</Text>
            <TouchableOpacity onPress={handleAddInstructor} style={styles.emptyButton}>
              <Text style={styles.emptyButtonText}>添加第一個導師</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <FlatList
            data={mentors}
            renderItem={renderInstructorCard}
            keyExtractor={(item) => item.id?.toString() || Math.random().toString()}
            contentContainerStyle={styles.instructorsList}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                colors={[Colors.primary]}
                tintColor={Colors.primary}
              />
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  gradHeader: {
    paddingTop: 12,
    paddingBottom: 16,
    paddingHorizontal: 16,
    borderBottomLeftRadius: 24,
    borderBottomRightRadius: 24,
  },
  headerRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  headerIconBtn: { width: 40, height: 40, alignItems: 'center', justifyContent: 'center' },
  headerTitle: { color: Colors.white, fontSize: 20, fontWeight: '800' },
  addPill: { backgroundColor: Colors.white, paddingHorizontal: 12, paddingVertical: 6, borderRadius: 16 },
  addPillText: { color: Colors.primary, fontWeight: '700', fontSize: 12 },

  content: {
    flex: 1,
    padding: 16,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: Colors.gray[600],
  },
  // 新卡片列表（貼合設計）
  itemCard: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: Colors.white,
    borderRadius: 16,
    padding: 12,
    marginBottom: 12,
    shadowColor: Colors.black,
    shadowOpacity: 0.06,
    shadowRadius: 6,
    shadowOffset: { width: 0, height: 3 },
    elevation: 2,
  },
  avatar: { width: 56, height: 56, borderRadius: 28, marginRight: 12 },
  name: { fontSize: 16, fontWeight: '700', color: Colors.gray[800], marginBottom: 6 },
  metaRow: { flexDirection: 'row', alignItems: 'center' },
  metaText: { color: Colors.gray[600], fontSize: 12 },
  badgeRow: { flexDirection: 'row', marginTop: 8 },
  badgeBlue: { backgroundColor: '#4F80FF', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12, marginRight: 8 },
  badgeText: { color: Colors.white, fontSize: 12, fontWeight: '600' },
  removePill: { backgroundColor: Colors.white, borderColor: Colors.primaryLight, borderWidth: 1, paddingHorizontal: 12, paddingVertical: 8, borderRadius: 16, marginLeft: 12 },
  removePillText: { color: Colors.primary, fontSize: 12, fontWeight: '700' },
  emptyState: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 32,
  },
  emptyTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: Colors.gray[700],
    marginTop: 16,
    marginBottom: 8,
  },
  emptyDescription: {
    fontSize: 16,
    color: Colors.gray[500],
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: 24,
  },
  emptyButton: {
    paddingHorizontal: 24,
    paddingVertical: 12,
    backgroundColor: Colors.primary,
    borderRadius: 8,
  },
  emptyButtonText: {
    color: Colors.white,
    fontWeight: '600',
  },
  instructorsList: {
    paddingVertical: 8,
  },
  instructorCard: {
    backgroundColor: Colors.white,
    borderRadius: 16,
    marginBottom: 16,
    elevation: 4,
    shadowColor: Colors.black,
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    overflow: 'hidden',
  },
  instructorHeader: {
    flexDirection: 'row',
    padding: 16,
    alignItems: 'center',
  },
  instructorImage: {
    width: 60,
    height: 60,
    borderRadius: 30,
    marginRight: 12,
  },
  instructorInfo: {
    flex: 1,
  },
  instructorName: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.gray[800],
    marginBottom: 4,
  },
  instructorCompany: {
    fontSize: 14,
    color: Colors.gray[600],
    marginBottom: 2,
  },
  instructorPhone: {
    fontSize: 14,
    color: Colors.gray[500],
  },
  moreButton: {
    width: 32,
    height: 32,
    alignItems: 'center',
    justifyContent: 'center',
  },
  qualificationsContainer: {
    paddingHorizontal: 16,
    paddingBottom: 12,
  },
  qualificationsLabel: {
    fontSize: 14,
    color: Colors.gray[600],
    marginBottom: 8,
  },
  qualificationsList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  qualificationBadge: {
    backgroundColor: Colors.primary + '20',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 12,
    marginRight: 8,
    marginBottom: 4,
  },
  qualificationText: {
    fontSize: 12,
    color: Colors.primary,
    fontWeight: '500',
  },
  instructorActions: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderTopColor: Colors.gray[200],
  },
  actionButton: {
    flex: 1,
    paddingVertical: 12,
    alignItems: 'center',
    borderRightWidth: 0.5,
    borderRightColor: Colors.gray[200],
  },
  removeButton: {
    borderRightWidth: 0,
  },
  actionButtonText: {
    fontSize: 14,
    color: Colors.primary,
    fontWeight: '500',
  },
  removeButtonText: {
    color: Colors.error,
  },
});
